import store from "@/store";
import { isWeChatBrowser } from "./utils.js";
// 登录授权模块

// #ifdef MP-WEIXIN

// 小程序静默登录
export function silenceLogin(callback = function() {}) {
    uni.removeStorageSync('permanent');
    uni.login({
        provider: "weixin",
        success: res => {
            this.$api.auth.mpLogin({
                jsCode: res.code
            }).then(res => {
                this.$setState("token", res.token);
                this.$api.user.userInfo().then(res => {
                    this.$setState('userInfo', res);
                    callback()
                })
            })
        }
    });
}


// 授权微信小程序用户信息
export function authWxMpUserInfo() {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            success: (loginRes) => {
                // code返回成功
                if (loginRes.code) {
                    // 保存code到vuex
                    store.commit('setState', {
                        name: 'loginCode',
                        data: loginRes.code
                    });
                }
            }
        });
        // 获取微信小程序用户信息
        uni.getUserProfile({
            desc: '用于完善会员资料',
            success: userProfile => {
                console.log('授权信息：', userProfile);
                // 保存登录信息到vuex
                store.commit('setState', {
                    name: 'userProfile',
                    data: userProfile
                });
                resolve(userProfile);
            },
            fail: err => {
                console.log('拒绝信息：', err);
                uni.showModal({
                    content: '您拒绝了微信授权,将无法使用小程序的功能,请重新授权,谢谢',
                    showCancel: false
                });
                reject(err);
            }
        });
    });
}

// 授权微信小程序电话号码
export function authWxMpPhone(authInfo) {
    return new Promise((resolve, reject) => {
        let jsCode = store.state.loginCode;
        let userProfile = store.state.userProfile;
        let refereeId = uni.getStorageSync('shareId') || '';
        if (jsCode && userProfile) {
            if (authInfo.encryptedData && userProfile.userInfo) {
                if (this.$api.auth.wxMpAuth && typeof this.$api.auth.wxMpAuth === 'function') {
                    this.$api.auth.wxMpAuth({
                        jsCode,
                        infoIv: userProfile.iv,
                        infoEncryptedData: userProfile.encryptedData,
                        iv: authInfo.iv,
                        encryptedData: authInfo.encryptedData,
                        refereeId
                    }).then(res => {
                        // 保存token
                        store.commit('setToken', res.token);
                        resolve();
                    }).catch(err => {
                        reject(err);
                    })
                } else {
                    uni.showToast({
                        icon: 'none',
                        title: '小程序授权注册接口未配置'
                    });
                    reject();
                }
            } else {
                uni.showToast({
                    icon: 'none',
                    title: '您拒绝了微信授权,将无法使用小程序的功能,请重新授权,谢谢',
                })
                reject();
            }
        } else {
            uni.showToast({
                icon: 'none',
                title: '授权信息有误',
            })
            reject();
        }
    });
}

// 微信小程序静默登录
export function wxMpSilenceLogin() {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            success: (loginRes) => {
                // code返回成功
                if (loginRes.code) {
                    if (this.$api.login.wxMpSilenceLogin && typeof this.$api.login
                        .wxMpSilenceLogin ===
                        'function') {
                        this.$api.login.wxMpSilenceLogin({
                            jsCode: loginRes.code
                        }).then(res => {
                            // 保存token
                            store.commit('setToken', res.token);
                            resolve();
                        }).catch(err => {
                            reject(err);
                        })
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: '静默登录接口未配置'
                        });
                        reject();
                    }
                }
            }
        });
    });
}
// #endif

// #ifdef APP-PLUS
// 微信客户端授权
export function weixinClientAuth(callback = function() {}) {
    plus.oauth.getServices(
        services => {
            let aweixin = services.filter(item => item.id === 'weixin')[0];
            if (!aweixin.authResult) {
                aweixin.authorize(
                    e => {
                        callback(e)
                    },
                    e => {
                        this.$toast(`微信授权失败:${e.message}`);
                    }, {
                        scope: 'snsapi_userinfo',
                        state: '123'
                    }
                );
            } else {
                this.$toast('已授权');
            }
        },
        e => {
            this.$toast('获取登录授权服务列表失败!');
        }
    );
}
// #endif

// #ifdef H5
// 微信公众号授权登录
// TODO 首先静默授权code通过后端接口判断用户是否已注册，如果未注册通过重定向微信授权换取code提交后端注册
export function wxPublicAuth(){
    let redirectUrl = encodeURIComponent(window.location.href);
window.location.href =
		`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${params.appid}&redirect_uri=${params.redirect_uri}&response_type=${params.response_type}&scope=${params.scope}&state=STATE#wechat_redirect`
};
// #endif
